//
//  OrderVC.swift
//  订单
//
//  Created by 千策万划-mini on 2025/4/28.
//

import Foundation

class OrderVC: BaseTableVC {

    var selectIndex = 0
    var modelDetail: ModelOrder = .init()

    // MARK: - lazy
    let listChannel: [ModelBtn] = [
        ModelBtn(code: "4", title: "All"),
        ModelBtn(code: "6", title: "Repayment"),
        ModelBtn(code: "7", title: "Applying"),
        ModelBtn(code: "5", title: "Finish"),
    ]
    lazy var viewNav: BaseNavView = {
        let result = BaseNavView()
        result.resetNavTitle(title: "Loan Order", leftView: nil, rightView: nil)
        result.leftTop = XY(0, 0)
        return result
    }()

    lazy var imageChannelBg: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(SCREEN_WIDTH, W(77))
        result.image = UIImage(named: "icon_order_channel_bg")
        return result
    }()

    lazy var scrollView: UIScrollView = {
        let result = UIScrollView()
        result.backgroundColor = .clear
        result.showsHorizontalScrollIndicator = false
        return result
    }()

    lazy var viewNoData: UIView = {
        let result = UIView()
        result.backgroundColor = .clear
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(SCREEN_WIDTH, tableView.height - 40)
        let view = OrderNoDataView()
        view.centerXCenterY = XY(SCREEN_WIDTH / 2, result.height / 2 - 25)
        view.blockApplyClick = { [weak self] in
            guard let self = self else { return }
            self.jumpToHomePage()
        }
        result.addSubview(view)
        return result
    }()

    // MARK: - viewDidLoad
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        requestList()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name(NOTICE_CHANGE_ORDER_TYPE), object: nil)
        configUI()
        addRefresh()
    }

    // 处理通知
    @objc func handleNotification(_ notification: Notification) {
        if let value = notification.object as? Int {
            print("收到的值 ------ : \(value)")
            // 遍历 listChannel 查找匹配的 code
            for (index, model) in listChannel.enumerated() {
                if let code = model.code, code == String(value) {
                    selectIndex = index
                    // 更新 UI 状态
                    for subview in scrollView.subviews {
                        if let btn = subview as? UIButton, btn.tag >= 0 {
                            btn.isSelected = (btn.tag == index)
                            if let label = btn.subviews.first(where: { $0 is OutlineLabel }) as? OutlineLabel {
                                label.resetView(
                                    title: UnPackStr(listChannel[btn.tag].title),
                                    textColor: COLOR_WHITE(),
                                    font: btn.isSelected ? UIFont.customExtraBoldFont(size: 14) : UIFont.customMediumFont(size: 14),
                                    shadowColor: UIColor(hex: btn.isSelected ? "#B05703" : "#2D0084"),
                                    outlineColor: UIColor(hex: btn.isSelected ? "#E28B0A" : "#2D0084")
                                )
                            }
                        }
                    }
                    // 刷新数据
                    refreshHeaderAll()
                    break
                }
            }
        }
    }

    override func addRefresh() {
        addRefreshHeader()
    }

    func configUI() {
        tableView.register(OrderCell.self, forCellReuseIdentifier: String(reflecting: OrderCell.self))
        view.addSubview(viewNav)
        view.addSubview(imageChannelBg)
        imageChannelBg.leftTop = XY(0, viewNav.bottom)
        tableView.height = SCREEN_HEIGHT - imageChannelBg.bottom - 86
        tableView.top = imageChannelBg.bottom
        scrollView.widthHeight = imageChannelBg.widthHeight
        scrollView.leftTop = XY(0, 0)
        imageChannelBg.addSubview(scrollView)
        let widthBtn = W(100)
        for i in 0 ..< listChannel.count {
            let btn = UIButton()
            btn.widthHeight = XY(widthBtn, W(48))
            btn.leftTop = XY(W(13) + (widthBtn + W(4)) * CGFloat(i), W(13))
            btn.setBackgroundImage(UIImage(named: "icon_order_type_normal"), for: .normal)
            btn.setBackgroundImage(UIImage(named: "icon_order_type_selected"), for: .selected)
            btn.tag = i
            btn.isSelected = i == 0
            btn.addTarget(self, action: #selector(btnChannelClick(_:)), for: .touchUpInside)
            let label = OutlineLabel()
            label.resetView(
                title: UnPackStr(listChannel[i].title),
                textColor: COLOR_WHITE(),
                font: i == 0 ? UIFont.customExtraBoldFont(size: 14) : UIFont.customMediumFont(size: 14),
                shadowColor: UIColor(hex: i == 0 ? "#B05703" : "#2D0084"),
                outlineColor: UIColor(hex: i == 0 ? "#E28B0A" : "#2D0084")
            )
            label.centerXCenterY = XY(btn.width / 2, btn.height / 2)
            btn.addSubview(label)
            scrollView.addSubview(btn)
            if i == listChannel.count - 1 {
                scrollView.contentSize = CGSize(width: btn.right + W(13), height: 0)
            }
        }
    }

    // MARK: - 点击事件
    func    jumpToHomePage() {
        if let tabBarController = tabBarController as? BaseTabbarController,
           let homeVC = tabBarController.viewControllers?[0]
        {
            tabBarController.selectedIndex = 0
            tabBarController.tabBarController(tabBarController, didSelect: homeVC)
        }
    }

    @objc func btnChannelClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        selectIndex = sender.tag
        for subview in scrollView.subviews {
            if let btn = subview as? UIButton, btn.tag >= 0 {
                btn.isSelected = (btn == sender)
                if let label = btn.subviews.first(where: { $0 is OutlineLabel }) as? OutlineLabel {
                    label.resetView(
                        title: UnPackStr(listChannel[btn.tag].title),
                        textColor: COLOR_WHITE(),
                        font: btn.isSelected ? UIFont.customExtraBoldFont(size: 14) : UIFont.customMediumFont(size: 14),
                        shadowColor: UIColor(hex: btn.isSelected ? "#B05703" : "#2D0084"),
                        outlineColor: UIColor(hex: btn.isSelected ? "#E28B0A" : "#2D0084")
                    )
                }
            }
        }
        // 计算目标按钮的中心位置
        let targetButton = sender as! UIButton
        let buttonCenterX = targetButton.center.x
        let scrollViewWidth = scrollView.bounds.width
        let targetOffsetX = buttonCenterX - scrollViewWidth / 2
        // 确保滚动位置在有效范围内
        let maxOffsetX = scrollView.contentSize.width - scrollViewWidth
        let finalOffsetX = max(0, min(targetOffsetX, maxOffsetX))
        // 使用动画滚动到目标位置
        UIView.animate(withDuration: 0.3) {
            self.scrollView.contentOffset = CGPoint(x: finalOffsetX, y: 0)
        }
        refreshHeaderAll()
    }

    // MARK: - tableView 代理
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return modelDetail.teasing.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: String(reflecting: OrderCell.self), for: indexPath) as! OrderCell
        cell.resetCellWithModel(modelDetail.teasing[indexPath.row])
        return cell
    }

    override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return OrderCell.fetchHeight(model: modelDetail.teasing[indexPath.row], className: nil, selectorName: "resetCellWithModel:")
    }

    override func tableView(_: UITableView, viewForHeaderInSection _: Int) -> UIView? {
        return modelDetail.teasing.isEmpty ? viewNoData : UIView()
    }

    override func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
        return modelDetail.teasing.isEmpty ? viewNoData.height : CGFLOAT_MIN
    }

    func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
        feedback()
        let model = modelDetail.teasing[indexPath.row]
        if model.prison.guessed.contains("http") {
            // http：跳转web
            let vc = BaseWebVC()
            vc.webUrl = model.prison.guessed
            vc.blockSwitchTabBarToHomePage = { [weak self] in
                guard let self = self else { return }
                self.jumpToHomePage()
            }
            GB_Nav?.pushViewController(vc, animated: true)
        } else {
            if model.prison.guessed.contains(LOCAL_PRODUCT_DETAIL_ROUTE) {
                if let quietRange = model.prison.guessed.range(of: "?", options: .backwards) {
                    let quietPart = model.prison.guessed[quietRange.upperBound...]
                    let pairs = quietPart.components(separatedBy: "&")
                    for pair in pairs {
                        let components = pair.components(separatedBy: "=")
                        if components.first == "carry" && components.count > 1 {
                            let makeValue = components.last?.trimmingCharacters(in: .whitespaces) ?? ""
                            let vc = ProductDetailVC()
                            vc.productCode = makeValue
                            GB_Nav?.pushViewController(vc, animated: true)
                            break
                        }
                    }
                }
            }
        }
    }

    // MARK: - request
    override func requestList() {
        HomeRequestApi.orderList(orderState: listChannel[selectIndex].code ?? "", delegate: self) { _, responseData in
            guard let res = responseData as? [String: Any] else { return }
            if let model = ModelOrder.deserialize(from: res) {
                self.modelDetail = model
                self.tableView.reloadData()
            }
        } failure: { _, _ in

        }
    }
}
